<template>
  <div class="person-info">
    <!-- 页面标题区域 -->
    <div class="page-header">
      <h2>个人信息</h2>
      <el-tag type="info">{{ getRoleName(userInfo.role) }}</el-tag>
    </div>

    <!-- 信息卡片 -->
    <div class="card-container">
      <el-card class="info-card" shadow="hover" v-loading="loading">
        <el-form
            :model="userInfo"
            :rules="rules"
            ref="userInfoForm"
            label-width="80px"
            class="info-form"
        >
          <!-- 头像上传区域 -->
          <el-form-item label="头像">
            <div class="avatar-upload">
              <input
                  type="file"
                  ref="avatarFileInput"
                  style="display: none"
                  accept="image/jpeg,image/png"
                  @change="handleAvatarFileChange"
              >
              <div v-if="showAvatarPreview" class="preview-container">
                <img :src="'/api' + (tempAvatar || userInfo.avatar)" class="avatar-image">
                <div class="image-overlay">
                  <el-button type="text" @click="triggerAvatarUpload">重新上传</el-button>
                  <el-button type="text" class="delete-btn" @click="removeAvatar">删除</el-button>
                </div>
              </div>
              <el-button v-else type="primary" @click="triggerAvatarUpload" size="small">
                <i class="el-icon-upload2"></i> 点击上传
              </el-button>
              <div class="el-upload__tip">只能上传jpg/png文件，且不超过2MB</div>
            </div>
          </el-form-item>

          <el-form-item label="用户名" prop="username">
            <el-input v-model="userInfo.username" disabled>
              <template slot="prepend">
                <i class="el-icon-user"></i>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="姓名" prop="name">
            <el-input v-model="userInfo.name">
              <template slot="prepend">
                <i class="el-icon-edit"></i>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="邮箱" prop="email">
            <el-input v-model="userInfo.email">
              <template slot="prepend">
                <i class="el-icon-message"></i>
              </template>
            </el-input>
          </el-form-item>

          <!-- 营业执照上传区域 -->
          <el-form-item label="营业执照" v-if="userInfo.role === 'MERCHANT'" prop="businessLicense">
            <div class="license-upload">
              <input
                  type="file"
                  ref="licenseFileInput"
                  style="display: none"
                  accept="image/jpeg,image/png"
                  @change="handleLicenseFileChange"
              >
              <div v-if="showLicensePreview" class="preview-container">
                <img :src="'/api' + (tempBusinessLicense || userInfo.businessLicense)" class="license-image">
                <div class="image-overlay">
                  <el-button type="text" @click="triggerLicenseUpload">重新上传</el-button>
                  <el-button type="text" class="delete-btn" @click="removeLicense">删除</el-button>
                </div>
              </div>
              <el-button v-else type="primary" @click="triggerLicenseUpload" size="small">
                <i class="el-icon-upload2"></i> 点击上传
              </el-button>
              <div class="el-upload__tip">只能上传jpg/png文件，且不超过2MB</div>
            </div>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="update" icon="el-icon-check">
              保存修改
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
import request from '@/utils/request';

export default {
  name: 'PersonInfo',
  inject: ['userInfo'],

  data() {
    return {
      loading: false,
      rules: {
        name: [
          { required: true, message: '姓名不能为空', trigger: 'blur' },
          { min: 2, max: 10, message: '姓名长度必须在2到10个字符之间', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '邮箱不能为空', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ]
      },
      // 头像相关临时状态
      tempAvatar: '',
      shouldDeleteAvatar: false,
      showAvatarPreview: !!this.userInfo.avatar,

      // 营业执照相关临时状态
      tempBusinessLicense: '',
      shouldDeleteLicense: false,
      showLicensePreview: !!this.userInfo.businessLicense
    };
  },

  methods: {
    getRoleName(role) {
      const roleMap = {
        'SUPER_ADMIN': '超级管理员',
        'ADMIN': '管理员',
        'MERCHANT': '商户',
        'USER': '普通用户'
      };
      return roleMap[role];
    },

    // 提交所有修改到服务器
    update() {
      this.$refs.userInfoForm.validate((valid) => {
        if (valid) {
          this.loading = true;

          // 处理头像修改
          if (this.tempAvatar) {
            this.userInfo.avatar = this.tempAvatar;
          }
          if (this.shouldDeleteAvatar) {
            this.userInfo.avatar = '';
          }

          // 处理营业执照修改
          if (this.tempBusinessLicense) {
            this.userInfo.businessLicense = this.tempBusinessLicense;
          }
          if (this.shouldDeleteLicense) {
            this.userInfo.businessLicense = '';
          }

          // 提交所有修改到服务器
          request.put("/user/" + this.userInfo.id, this.userInfo).then(response => {
            this.loading = false;
            if (response.code == '0') {
              this.$message({
                type: 'success',
                message: '信息保存成功!'
              });
              // 更新本地存储的用户信息
              localStorage.setItem("frontUser", JSON.stringify(this.userInfo));
              // 通知父组件更新用户信息
              this.$emit("update:user", this.userInfo);

              // 重置所有临时状态
              this.resetTempState();
            } else {
              this.$message({
                type: 'error',
                message: response.msg
              });
            }
          }).catch(() => {
            this.loading = false;
          });
        } else {
          return false;
        }
      });
    },

    // 重置所有临时状态
    resetTempState() {
      this.tempAvatar = '';
      this.shouldDeleteAvatar = false;
      this.showAvatarPreview = !!this.userInfo.avatar;

      this.tempBusinessLicense = '';
      this.shouldDeleteLicense = false;
      this.showLicensePreview = !!this.userInfo.businessLicense;
    },

    // 头像上传相关方法
    triggerAvatarUpload() {
      this.$refs.avatarFileInput.click();
    },

    async handleAvatarFileChange(e) {
      const file = e.target.files[0];
      if (!file) return;

      // 验证文件类型和大小
      const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPGOrPNG) {
        this.$message.error('只能上传 JPG/PNG 格式的图片!');
        return;
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!');
        return;
      }

      this.loading = true;
      try {
        // 创建 FormData
        const formData = new FormData();
        formData.append('file', file);

        const res = await request.post('/file/upload/img', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });

        if (res.code === '0') {
          this.tempAvatar = res.data;
          this.shouldDeleteAvatar = false;
          this.showAvatarPreview = true;
          this.$message.success('头像上传成功，保存修改后生效');
        } else {
          this.$message.error(res.msg || '头像上传失败');
        }
      } catch (error) {
        console.error('头像上传失败:', error);
        this.$message.error('头像上传失败');
      } finally {
        this.loading = false;
      }
    },

    removeAvatar() {
      this.$confirm('确认删除头像?', '提示', {
        type: 'warning'
      }).then(() => {
        this.shouldDeleteAvatar = true;
        this.showAvatarPreview = false;
        this.tempAvatar = '';
        this.$message.success('头像将在保存修改后删除');
      }).catch(() => {});
    },

    // 营业执照上传相关方法
    triggerLicenseUpload() {
      this.$refs.licenseFileInput.click();
    },

    async handleLicenseFileChange(e) {
      const file = e.target.files[0];
      if (!file) return;

      // 验证文件类型和大小
      const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPGOrPNG) {
        this.$message.error('只能上传 JPG/PNG 格式的图片!');
        return;
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!');
        return;
      }

      this.loading = true;
      try {
        // 创建 FormData
        const formData = new FormData();
        formData.append('file', file);

        const res = await request.post('/file/upload/img', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });

        if (res.code === '0') {
          this.tempBusinessLicense = res.data;
          this.shouldDeleteLicense = false;
          this.showLicensePreview = true;
          this.$message.success('营业执照上传成功，保存修改后生效');
        } else {
          this.$message.error(res.msg || '营业执照上传失败');
        }
      } catch (error) {
        console.error('营业执照上传失败:', error);
        this.$message.error('营业执照上传失败');
      } finally {
        this.loading = false;
      }
    },

    removeLicense() {
      this.$confirm('确认删除营业执照?', '提示', {
        type: 'warning'
      }).then(() => {
        this.shouldDeleteLicense = true;
        this.showLicensePreview = false;
        this.tempBusinessLicense = '';
        this.$message.success('营业执照将在保存修改后删除');
      }).catch(() => {});
    }
  }
};
</script>

<style scoped>
/* 样式保持不变 */
.person-info {
  padding: 24px;
  background-color: #fff8f0;
  min-height: calc(100vh - 60px);
  animation: fadeIn 0.3s ease-in-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h2 {
  font-size: 24px;
  font-weight: 500;
  color: #E67E22;
  margin: 0;
  margin-right: 15px;
}

.card-container {
  max-width: 800px;
  margin: 0 auto;
}

.info-card {
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  background-color: white;
}


.info-form {
  max-width: 600px;
  margin: 0 auto;
  padding: 30px 20px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #E67E22;
}

:deep(.el-input__inner) {
  border-radius: 8px;
  border: 1px solid #f0d5b3;
  transition: all 0.3s;
}

:deep(.el-input__inner:focus) {
  border-color: #F39C12;
  box-shadow: 0 0 0 2px rgba(243, 156, 18, 0.2);
}

:deep(.el-input-group__prepend) {
  background-color: #fff4e0;
  border-color: #f0d5b3;
  color: #d3b993;
  padding: 0 15px;
}

:deep(.el-button) {
  padding: 12px 20px;
  font-size: 14px;
  border-radius: 8px;
  width: 100%;
  transition: all 0.3s;
}

:deep(.el-button--primary) {
  background-color: #F39C12;
  border-color: #F39C12;
}

:deep(.el-button--primary:hover) {
  background-color: #E67E22;
  border-color: #E67E22;
}

:deep(.el-tag) {
  height: 28px;
  line-height: 26px;
  padding: 0 10px;
  font-size: 13px;
  background-color: rgba(243, 156, 18, 0.1);
  border-color: rgba(243, 156, 18, 0.2);
  color: #F39C12;
}

.license-upload {
  text-align: center;
}

.preview-container {
  position: relative;
  display: inline-block;
  /* 营业执照保持原尺寸 */
  width: 280px;
  height: 396px;
}

/* 新增头像预览容器样式 */
.avatar-upload .preview-container {
  width: 120px;
  height: 120px;
  margin: 0 auto 10px;
}

.license-image {
  width: 280px;
  height: 396px;
  object-fit: contain;
  border: 1px solid #f0d5b3;
  border-radius: 8px;
  transition: all 0.3s;
  background-color: #fff4e0;
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  opacity: 0;
  transition: all 0.3s;
  border-radius: 8px;
  flex-direction: column;
  gap: 10px;
}

/* 头像覆盖层适配圆形 */
.avatar-upload .image-overlay {
  border-radius: 50%;
}

.preview-container:hover .image-overlay {
  opacity: 1;
}

.image-overlay .el-button {
  color: #fff;
  margin: 0 10px;
}

.image-overlay .delete-btn {
  color: #f56c6c;
}

.el-upload__tip {
  font-size: 12px;
  color: #d3b993;
  margin-top: 5px;
}

.avatar-upload {
  text-align: center;
}

.avatar-image {
  width: 120px;
  height: 120px;
  object-fit: cover;
  border: 1px solid #f0d5b3;
  border-radius: 50%;
  transition: all 0.3s;
  background-color: #fff4e0;
}
</style>